import taskService from '@/api/taskService';
const state = {
    tasks: [],//任务数组
    loading: false,//是否正在调用接口
    currentFilter: 'all',//当前的过滤器，或者说过滤类型
    newTaskDialogVisible: false,
}
const getters = {
    filteredTasks: (state) => {
        return state.tasks.filter(task => state.currentFilter === 'all' ||
            task.status === state.currentFilter);
    }
}
const actions = {
    async retrieveTasks({ commit, state }) {
        try {
            state.loading = true;
            let result = await taskService.getTasks();
            commit('setTasks', result);
        } catch (error) {
            this._vm.$message({
                type: "error",
                message: error.message,
            });
        } finally {
            state.loading = false;
        }
    },
    async handleDelete({ state, dispatch }, id) {
        try {
            state.loading = true;
            await taskService.deleteTask(id);
            dispatch('retrieveTasks');
            this._vm.$message.success('任务删除成功');
        } catch (error) {
            this._vm.$message.error('任务删除失败');
        } finally {
            state.loading = false;
        }
    },
    async handleComplete({ dispatch, state }, id) {
        try {
            state.loading = true;
            await taskService.updateTask(id);
            dispatch('retrieveTasks');
            this._vm.$message.success('任务成功完成');
        } catch (error) {
            this._vm.$message.error('任务完成失败');
        } finally {
            state.loading = false;
        }
    },
    async handleNewTask({ dispatch, commit }, { description, formatted_expected_completion_time }) {
        await taskService.createTask(description, formatted_expected_completion_time);
        dispatch('retrieveTasks');
        commit('setNewTaskDialogVisible', false);
    },
}
const mutations = {
    setTasks(state, tasks) {
        state.tasks = tasks;
    },
    setLoading(state, loading) {
        state.loading = loading;
    },
    setFilter(state, currentFilter) {
        state.currentFilter = currentFilter;
    },
    setNewTaskDialogVisible(state,newTaskDialogVisible) {
        state.newTaskDialogVisible = newTaskDialogVisible;
    }
}
export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}